#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:1静态web服务器.py
# author: 马国鑫
# datetime:2022/4/18 21:49
# software: PyCharm

"""
this is function  description 
"""

# import module your need

import socket

# 创建电话
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 端口复用
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)

# 绑定地址
tcp_server_socket.bind(("", 8080))

# 设置监听
tcp_server_socket.listen(128)

while True:
    # 等待接受
    client_socket, addr = tcp_server_socket.accept()
    recv_data = client_socket.recv(1000000)

    if len(recv_data) == 0:
        print('客户端关闭')
        break

    recv_data = recv_data.decode()
    print(recv_data)

    # 对请求报文进行切割
    path_list = recv_data.split(' ')
    # print(path_list)
    # 请求资源路径
    request_path = path_list[1]

    # 异常捕获，防止出现异常服务器直接崩溃
    try:
        # 打开资源文件,二进制打开
        f = open('./static' + request_path, 'rb')
        # 存放了图片资源
        file_data = f.read()
        f.close()
    except Exception as e:
        # 证明文件不存在
        # 浏览器访问的资源不存在
        print("异常信息", e)
        # 访问不成功的情况下响应报文
        response_line = "HTTP/1.1 404 NOT FOUND\r\n"
        response_header = "server:py1.0\r\n"
        response_body = "not found i am sorry"
        response_data = response_line + response_header + "\r\n" + response_body
        # 发送数据
        client_socket.send(response_data.encode())
    else:
        # 浏览器能够找到
        # 组装响应报文
        # 响应行
        response_line = "HTTP/1.1 200 OK\r\n"
        response_header = "server:py1.0\r\n"
        response_body = file_data

        response_data = (response_line + response_header + "\r\n").encode() + response_body

        # 发送数据
        client_socket.send(response_data)

    # 关闭
    client_socket.close()


